package com.fyzk.activity.lottery.basketball;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.jc.football.guoguan.JC_GuoGuanDialog;
import com.fyzk.activity.lottery.jc.football.guoguan.JC_GuoGuanInfor;
import com.fyzk.activity.lottery.recommend_order.RecommendTypePopupwindow;
import com.fyzk.activity.zhifu.JCBasePayActivity;
import com.fyzk.activity.zhifu.ShaiDanActivity;
import com.fyzk.adapter.JCLQSFPayAdapter;
import com.fyzk.interfaces.OnBasketPayTeamDeleteListener;
import com.fyzk.model.JCLQMatchData;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.utils.jc.JLPrizeComputeUtil;
import com.fyzk.view.ASView;
import com.tyjc.lottery.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import http.DataUtil.text.TextUtil;

/**
 * 竞彩篮球的投注基类
 */
public class JCLQPayActivity extends JCBasePayActivity implements ASView.OnValueChangedLisener, OnBasketPayTeamDeleteListener {

    private TextView ziXuan;
    private EditText mEtMemo;
    protected ListView listView;
    private ASView touBei;

    protected List<JCLQMatchData> jcInfors = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        initInfor();    //必须放在最上面
        super.onCreate(savedInstanceState);
        initGuoGuanView();
        setDefaultGG();
    }

    private void setDefaultGG() {
        int changci = jcInfors.size();
        if (changci > getMaxGuoGuan()) {
            changci = getMaxGuoGuan();
        }
        JC_GuoGuanDialog.isDuoChuan = false;
        JC_GuoGuanDialog.result = changci + "串" + 1;
        tv_guoGuanStyle.setText(JC_GuoGuanDialog.result);
        setBtmView();
    }

    /**
     * 初始化infor
     */
    protected void initInfor() {
        for (int i = 0; i < JCLQFragmentActivityI.matchs.size(); i++) {
            JCLQMatchData info = JCLQFragmentActivityI.matchs.get(i);
            if (info.clickNum > 0) {
                jcInfors.add(info);
            }
        }
    }

    @Override
    public void onBackPressed() {
        finish();//支付页退出不做任何操作
    }

    @Override
    /**获取投注的注码*/
    protected String getContent() {
        List<String> chuans = JC_GuoGuanInfor.getChuanIds(JC_GuoGuanDialog.result, isDanguan);
        String content = "";
        for (int i = 0; i < chuans.size(); i++) {
            content += lotteryId + "" + wanFa + chuans.get(i) + "-";// 301012001-
            String n = "";
            for (int j = 0; j < JCLQFragmentActivityI.matchs.size(); j++) {
                JCLQMatchData info = JCLQFragmentActivityI.matchs.get(j);
                StringBuffer danChang = new StringBuffer();
                if (info.clickNum != 0) {
                    danChang.append(info.getMatchNum());
                    danChang.append("(");

                    switch (lotteryId) {
                        case LotteryIDUtils.JLRSF_LOTTERY_ID_INT:
                            if (info.splInfos.get(info.LETVS_0).isSel) {
                                danChang.append("0,");
                            }
                            if (info.splInfos.get(info.LETVS_3).isSel) {
                                danChang.append("3,");
                            }
                            break;
                        case LotteryIDUtils.JLSF_LOTTERY_ID_INT:
                            if (info.splInfos.get(info.VS_0).isSel) {
                                danChang.append("0,");
                            }
                            if (info.splInfos.get(info.VS_3).isSel) {
                                danChang.append("3,");
                            }
                            break;
                    }


                    danChang = danChang.deleteCharAt(danChang.length() - 1);
                    danChang.append(")");
                }

                if (!danChang.toString().equals("")) {
                    n += danChang + "|";
                }
            }
            if (!n.equals("")) {
                n = n.substring(0, n.length() - 1);
                n += "^";
            }
            content += n + "!";
        }
        if (!content.equals("")) {
            content = content.substring(0, content.length() - 1);
        }
        return content;
    }

    @Override
    protected void clear() {
        JC_GuoGuanDialog.result = getString(R.string.guoguan_hint);
        tv_guoGuanStyle.setText(JC_GuoGuanDialog.result);

        for (JCLQMatchData data : jcInfors) {
            for (JCLQMatchData.SPInfo info : data.plInfos) {
                info.isSel = false;
            }
            data.clickNum = 0;
            data.setSfcNum(0);
        }
        jcInfors.clear();
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void adapterChange() {
        adapter.notifyDataSetChanged();
    }

    @Override
    public int getOneAmount() {
        return 2;
    }

    /**
     * 初始化对阵列表的Adapter
     */
    protected void setAdapter() {
        isDanguan = getIntent().getBooleanExtra(IntentParamUtils.TYPE_GUOGUAN, false);
        adapter = new JCLQSFPayAdapter(this, isDanguan,
                jcInfors, handler, lotteryId, this);
        listView.setAdapter(adapter);
    }

    @Override
    protected View initCenterView() {
        View view = LayoutInflater.from(this)
                .inflate(R.layout.jclq_zhifu, null);
        // 优惠劵
        LinearLayout coupon_ll = view.findViewById(R.id.zhifu_coupon_ll);
        coupon_ll.addView(couponZhifuView);

        mEtMemo = view.findViewById(R.id.basketballPayUI_etMemo);
        ziXuan = view.findViewById(R.id.jc_zhifu_center_addmore);
        tv_guoGuanStyle = view.findViewById(R.id.jc_zhifu_ggfs);
        listView = view.findViewById(R.id.jc_zhifu_listview);
        setAdapter();
        listView.addFooterView(getListFooterView());
        touBei = view
                .findViewById(R.id.jc_zhifu_et_toubei);
        touBei.setLeftText("投");
        touBei.setRightText("倍");
        touBei.setOnValueChangedLisener(this);
        // 事件
        ziXuan.setOnClickListener(clickListener);
        tv_guoGuanStyle.setOnClickListener(clickListener);

        // 晒单方式
        final TextView recommendType_tv = view.findViewById(R.id.jc_zhifu_recommendtype_tv);
        TextView recommendType_line_tv = view.findViewById(R.id.jc_zhifu_recommendtype_line_tv);  // 分割线
        if (App.isBaskOrder) {
            recommendType_tv.setVisibility(View.VISIBLE);
            recommendType_line_tv.setVisibility(View.VISIBLE);
        }else{
            mEtMemo.setVisibility(View.GONE);
        }

        final String[] rr_type = {"公开推荐", "不发起推荐", "保密推荐"};
        if (recommendTypePopupwindow == null) {
            recommendTypePopupwindow = new RecommendTypePopupwindow(getContext(), rr_type);
            recommendTypePopupwindow.setListener(new RecommendTypePopupwindow.RecommendTypeItemListener() {
                @Override
                public void onItem(int position) {
                    recommendType = position;
                    recommendType_tv.setText(rr_type[position]);
                    if (recommendType == 1) {
                        btm_sure.setText("支付");
                    } else {
                        btm_sure.setText("购彩并晒单");
                    }
                }
            });
        }
        recommendType_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(JCLQPayActivity.this, ShaiDanActivity.class);
                intent.putExtra("amount", getAmount());
                intent.putExtra("recommendType",recommendType);
                intent.putExtra("proportions",proportions);
                intent.putExtra("proportionType",proportionType);
                intent.putExtra("isShowAmt",isShowAmt);
                intent.putExtra("isShowMaxSP",isShowMaxSP);
                startActivityForResult(intent, IntentParamUtils.JC_GENDAN);
            }
        });
        return view;
    }

    @Override
    public String getMemo() {
        String memo = mEtMemo.getText().toString();
        if (TextUtil.isEmpty(memo))
            return super.getMemo();
        return memo;
    }

    private RecommendTypePopupwindow recommendTypePopupwindow;

    private String typeStrs[] = null;

    @Override
    public void setBtmView() {
        super.setBtmView();
        JLPrizeComputeUtil util = new JLPrizeComputeUtil(this, jcInfors, lotteryId);
        double prizeMax = 0.0;
        double prizeMin = 0.0;
        if (getZhushu() > 0) {
            if (isDanguan) {
                prizeMin = util.getDanPrize(false);
                prizeMax = util.getDanPrize(true);
            } else {
                if(JC_GuoGuanDialog.isDuoChuan){
                    typeStrs = JC_GuoGuanDialog.duo_result.split("\\,");
                    int teamNum = JC_GuoGuanDialog.team_num;
                    if (null != typeStrs) {
                        // 存放最小预计彩金
                        List<Double> prizeMinData = new ArrayList<>();
                        List<List<JCLQMatchData>> groupInfoData = getGroupInfoData(jcInfors, teamNum);
                        for(int j=0;j<groupInfoData.size();j++){
                            List<JCLQMatchData> childInfoData = groupInfoData.get(j);
                            for (int i = 0; i < typeStrs.length; i++) {
                                if (typeStrs[i].contains("串")) {
                                    prizeMax += util.getDoublePrize2(typeStrs[i], childInfoData, true);
                                    double tempMinPrize = util.getDoublePrize2(typeStrs[i], childInfoData, false);
                                    prizeMinData.add(tempMinPrize);
                                }
                            }
                        }

                        // 获取集合中最小的预计彩金
                        for (int i=0;i<prizeMinData.size();i++){
                            double prize = prizeMinData.get(i);
                            if(Collections.min(prizeMinData) == prize){
                                prizeMin += prize;
                            }
                        }
                    }
                }else{
                    typeStrs = JC_GuoGuanDialog.result.split("\\,");
                    if (null != typeStrs) {
                        for (int i = 0; i < typeStrs.length; i++) {
                            if (typeStrs[i].contains("串")) {
                                prizeMax += util.getDoublePrize(typeStrs[i], true);
                                if (prizeMin == 0) {
                                    prizeMin = util.getDoublePrize(typeStrs[i], false);
                                }
                            }
                        }
                    }
                }
            }
            minPrize = prizeMin * getBeishu();
            maxBounusPrize = prizeMax * getBeishu();
            String prizeMinStr = PublicMethod.formatMoney(prizeMin * getBeishu() * 100);
            String prizeMaxStr = PublicMethod.formatMoney(prizeMax * getBeishu() * 100);
            String prizeStr = "预计奖金：<font color='#fd4a4a'>" + prizeMinStr + "~" + prizeMaxStr + "</font>米";
            expectedPrize = prizeMinStr + "~" + prizeMaxStr;
            btm_leftMoney.setText(Html.fromHtml(prizeStr));
        } else {
            btm_leftMoney.setText("至少选择一注");
        }

    }

    // 用于存放K场次M串，排列组合方式信息
    public List<List<JCLQMatchData>> tempGroupData;
    private List<List<JCLQMatchData>> getGroupInfoData(List<JCLQMatchData> infos, int teamNum) {
        List<List<JCLQMatchData>> groupInfoData = new ArrayList<>();
        // 保存设置为胆的比赛场次信息
        List<JCLQMatchData> danInfoData = new ArrayList<>();
        // 保存不是胆的比赛场次信息
        List<JCLQMatchData> noDanInfoData = new ArrayList<>();

        // 例如选择8场比赛，8串n过关方式
        if(infos.size() == teamNum){
            groupInfoData.add(infos);
        }else{
            for (int i = 0; i < infos.size(); i++) {
                JCLQMatchData tempInfo = infos.get(i);
                int checkNum = tempInfo.clickNum;
                if (checkNum > 0) {
                    if(tempInfo.isDan()){
                        danInfoData.add(tempInfo);
                    }else{
                        noDanInfoData.add(tempInfo);
                    }
                }
            }
            getGroupSort(noDanInfoData, teamNum - danInfoData.size());

            for(int i=0;i<tempGroupData.size();i++){
                List<JCLQMatchData> tempInfoData = tempGroupData.get(i);
                // 将作为胆的比赛场次信息添加到每一个排列信息中
                tempInfoData.addAll(danInfoData);
                groupInfoData.add(tempInfoData);
            }
        }
        return groupInfoData;
    }

    /**
     * K场次M串排列组合方式
     * 例如 通常请款下（不加胆时）：选择8场比赛，3串n过关方式，
     *     8场中任选3场有56种情况
     * @param info      选择的场次信息
     * @param teamNum  M串 M的数量
     */
    public void getGroupSort(List<JCLQMatchData> info, int teamNum) {
        tempGroupData = new ArrayList<>();
        if (info == null || info.size() == 0) {
            return;
        }
        List<JCLQMatchData> list = new ArrayList();
        combine(info, 0, teamNum, list);
    }

    // 从字符数组中第begin个字符开始挑选number个字符加入list中
    public void combine(List<JCLQMatchData> info, int begin, int number, List<JCLQMatchData> list) {
        if (number == 0) {
            // 将每一种排列组合结果保存在tempGroupData中
            tempGroupData.add(new ArrayList<JCLQMatchData>(list));
            return;
        }
        if (begin == info.size()) {
            return;
        }
        list.add(info.get(begin));
        combine(info, begin + 1, number - 1, list);
        list.remove(info.get(begin));
        combine(info, begin + 1, number, list);
    }

    @Override
    public void initGuoGuanView() {
        super.initGuoGuanView();
        if (isDanguan) {
            tv_guoGuanStyle.setText("单关");
        } else {
            tv_guoGuanStyle.setText(JC_GuoGuanDialog.result);
        }
    }

    protected int getMaxGuoGuan() {
        switch (lotteryId) {
            case LotteryIDUtils.JLDXF_LOTTERY_ID_INT:
                return 8;
            case LotteryIDUtils.JLRSF_LOTTERY_ID_INT:
                return 8;
            case LotteryIDUtils.JLSF_LOTTERY_ID_INT:
                return 8;
            case LotteryIDUtils.JLSFC_LOTTERY_ID_INT:
                return 4;
            case LotteryIDUtils.JLHH_LOTTERY_ID_INT:
                boolean hasSFC = false;
                for (JCLQMatchData matchData : jcInfors) {
                    if(matchData.getSfcNum()>0){
                        hasSFC = true;
                    };
                }
                if(hasSFC){
                    return 4;
                }else{
                    return 8;
                }
        }
        return 8;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case IntentParamUtils.CHANGE_GUOGUAN:
                tv_guoGuanStyle.setText(JC_GuoGuanDialog.result);
                break;
            case 0x6:
                isDanguan = data.getBooleanExtra(IntentParamUtils.TYPE_GUOGUAN,
                        false);
                initGuoGuanView();
                break;
            case IntentParamUtils.JC_GENDAN:
                if (resultCode == IntentParamUtils.OK) {
                    recommendType = data.getIntExtra("recommendType", -1);
                    if (recommendType == 1) {
                        btm_sure.setText("支付");
                    } else {
                        btm_sure.setText("购彩\n并晒单");
                    }
                }
                break;
        }
        adapterChange();
    }

    OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.jc_zhifu_center_addmore:// 自选
                    addMoreMatch();
                    break;

                case R.id.jc_zhifu_ggfs:// 选择过关方式
                    if ((!isDanguan && changCi < 2) || (isDanguan && changCi < 1)) {
                        AppToast.getToast().show("请添加更多场比赛");
                        break;
                    }
                    if (!isDanguan) {
                        Intent intent = new Intent(JCLQPayActivity.this,
                                JC_GuoGuanDialog.class);
                        intent.putExtra(IntentParamUtils.JC_CHANGCI, changCi);
                        intent.putExtra(IntentParamUtils.JC_MAXGUOGUAN,
                                getMaxGuoGuan());
                        intent.putExtra(IntentParamUtils.LOTTERYID, lotteryId);
                        startActivityForResult(intent, IntentParamUtils.CHANGE_GUOGUAN);
                    }
                    break;
            }
        }

    };


    private void addMoreMatch() {
        setResult(IntentParamUtils.JC_ADDMORE);
        finish();
    }


    @Override
    public void onValueChanged(ASView view, int value) {
        beishu = value;
        setBtmView();
    }

    @Override
    public void onDelete(JCLQMatchData tag) {
        JC_GuoGuanDialog.result = JC_GuoGuanDialog.GG_RESULT;
        initGuoGuanView();
    }

}


